package arrAndstr;

import java.util.ArrayList;
import java.util.List;

/*
    114. 二叉树展开为链表
 */
public class T114 {

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public static void main(String[] args) {
        TreeNode node = new TreeNode(1);
        node.left = new TreeNode(2);
        node.left.left = new TreeNode(3);
        node.left.right = new TreeNode(4);
        node.right = new TreeNode(5);
        node.right.right = new TreeNode(6);

        flatten(node);
    }

    public static void flatten(TreeNode root) {
        if (root == null)  return;

        List<Integer> list = new ArrayList<>();
        preSearch(root, list);

        for (int i = 1; i < list.size(); i++) {
            root.left = null;
            root.right = new TreeNode(list.get(i));
            root = root.right;
        }

    }

    private static void preSearch(TreeNode root, List<Integer> list) {
        if (root == null)   return;

        list.add(root.val);
        preSearch(root.left, list);
        preSearch(root.right, list);
    }

}
